package com.yinxin.thread;

/**
 * @author yinxin
 * @version 1.0
 * @Description:
 * @date 2022/6/2921:31
 */
public class CompareAndSwap {

      private int value;

      //获取内存值
      public synchronized int get() {
         return value;
      }

      //交换
      public synchronized int compareAndSwap(int expectedValue, int newValue) {
         //获得内存值
         int oldValue = value;
         //比较
         if (oldValue == expectedValue) {
            this.value = newValue;
         }
         return oldValue;
      }
      //cas
      public synchronized boolean compareAndSet(int expectedValue, int newValue) {
         return expectedValue == compareAndSwap(expectedValue, newValue);
      }
   }

   class TestCompareAndSwap {
      private static CompareAndSwap cas = new CompareAndSwap();

      public static void main(String[] args) {
         for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
               public void run() {
                  int expectedValue = cas.get();
                  boolean b = cas.compareAndSet(expectedValue, (int) (Math.random() * 101));
                  System.out.println(b);
               }
            }).start();
         }
      }
}
